package com.LeeCode;

import java.util.HashMap;
import java.util.Map;

/**
 * 连接两字母单词得到的最长回文串
 */

public class Code2131 {
    public static void main(String[] args) {
        String[] words = {"aa", "bb", "bb"};

        System.out.println(new Code2131().longestPalindrome(words));

    }

    public int longestPalindrome(String[] words) {
        int length = 0;
        boolean center = false;
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String word = entry.getKey();
            int value = entry.getValue();

            if (word.charAt(0) == word.charAt(1)) {
                if (value % 2 == 1) {
                    center = true;
                }
                length += (value / 2) * 2 * 2;
            } else {
                String reversed = new StringBuilder(word).reverse().toString();
                if (map.containsKey(reversed)) {
                    int reversedValue = map.get(reversed);
                    length += Math.min(reversedValue, value) * 4;

                    map.put(word, 0);
                    map.put(reversed, 0);
                }
            }
        }

        if (center) {
            length += 2;
        }
        return length;
    }
}
